'use strict'; //严格模式
const express = require('express');
const path = require('path');
const xtpl = require('xtpl');
const moment = require('moment');


const nodemailer = require("nodemailer");
const smtpTransport = require('nodemailer-smtp-transport');
const wellknown = require("nodemailer-wellknown");
const config = wellknown("163");   //所选择的第三方服务

const db = require(path.join(__dirname,"../configs/database.js"));


//跳转方法
module.exports.showMsg = function(res,msg='',url=false){
    res.setHeader("Content-Type","text/html;charset=utf-8");
    if(url)
    {
        res.end(`<script>alert('${msg}');location.href='${url}';</script>`);
        return false;
    }else{
        res.end(`<script>alert('${msg}');history.go(-1);</script>`);
        return false;
    }
};


//模板赋值
module.exports.assign = function(obj)
{
    xtpl.renderFile(
        obj.template,
        obj.data,
        function(err,content){
            obj.res.setHeader("Content-Type","text/html;charset=utf-8");
            obj.res.end(content);
        }
    );
};


//生成随机数
module.exports.randomString = function (len = 4) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
};


module.exports.signupEmail = function(obj,callback)
{
    config.auth = {
        user:'dancefunk@163.com',  //邮件账号
        pass:'h1801123'   //这里密码不是qq,163密码，是你设置的smtp授权密码
    };

    var transporter = nodemailer.createTransport(smtpTransport(config));

    var mailOptions = {
        from:"dancefunk@163.com",   //发送方的邮件地址
        to:obj.email,    //收件人的邮件地址
        subject:obj.subject,  //邮件主题
        text:"text plain",    //邮件文档类型
        html:obj.content   //邮件正文内容
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function(error, info){
        callback(error,info);
    });

};